package com.sofurry;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

/**
 * Define a simple widget that shows the Wiktionary "Word of the day." To build
 * an update we spawn a background {@link Service} to perform the API queries.
 */
public class SFStats extends AppWidgetProvider {
	
	@Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        // To prevent any ANR timeouts, we perform the update in a service
        context.startService(new Intent(context, UpdateService.class));
    }
    
    public static class UpdateService extends Service {
    	public static final int AJAXTYPE_APIERROR = 5;
    	@Override
        public void onStart(Intent intent, int startId) {
            // Build the widget update for today
            RemoteViews updateViews = buildUpdate(this);
            
            // Push update for this widget to the home screen
            ComponentName thisWidget = new ComponentName(this, SFStats.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, updateViews);
        }

        /**
         * Build a widget update to show the current Wiktionary
         * "Word of the day." Will block until the online API returns.
         */
        public RemoteViews buildUpdate(Context context) {
            // Pick out month names from resources
            Resources res = context.getResources();
            

            RemoteViews updateViews = null;
            
            Map<String, String> results = getProfileStats();

            String viewCount = results.get("profileviews");
            String watchCount = results.get("watches");
            
            if (viewCount != "") {
                // Build an update that holds the updated widget contents
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_sf);
                
//                updateViews.setTextViewText(R.id.word_title, "title");
//                updateViews.setTextViewText(R.id.word_type, "type");
                updateViews.setTextViewText(R.id.definition, viewCount + " views");
                
//                // When user clicks on widget, launch to Wiktionary definition page
//                String definePage = res.getString(R.string.template_define_url,
//                        Uri.encode(wordTitle));
//                Intent defineIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(definePage));
//                PendingIntent pendingIntent = PendingIntent.getActivity(context,
//                        0 /* no requestCode */, defineIntent, 0 /* no flags */);
//                updateViews.setOnClickPendingIntent(R.id.widget, pendingIntent);
                
            } else {
                // Didn't find word of day, so show error message
                updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_message);
                CharSequence errorMessage = context.getText(R.string.widget_error);
                updateViews.setTextViewText(R.id.message, errorMessage);
            }
            return updateViews;
        }
        
        @Override
        public IBinder onBind(Intent intent) {
            // We don't need to bind to this service
            return null;
        }

    	private Map<String, String> getProfileStats() {
    		Random random = new Random();
    		String username = ""; // TODO: load from preference
    		String password = ""; // TODO: load from preference

    		if (username != null && username != "") {
    			Authentication.updateAuthenticationInformation(username, password);
    		}
    		String requestUrl = "http://sofurry.com/ajaxfetch.php";
    		Map<String, String> requestParameters = new HashMap<String, String>();
    		requestParameters.put("f", "getprofilestats");

    		try {
    			// add authentication parameters to the request
    			HttpResponse response;
    			Map<String, String> authRequestParameters = Authentication.addAuthParametersToQuery(requestParameters);
    			response = HttpRequest.doPost(requestUrl, authRequestParameters);
    			String httpResult = EntityUtils.toString(response.getEntity());
    			ArrayList<String> resultList = new ArrayList<String>();
    			if (Authentication.parseResponse(httpResult) == false) {
    				Log.d("getNewImageUrl", "RE-SENDING REQUEST with new auth credentials");
    				// Retry request with new otp sequence if it failed for the first time
    				authRequestParameters = Authentication.addAuthParametersToQuery(requestParameters);
    				response = HttpRequest.doPost(requestUrl, authRequestParameters);
    				httpResult = EntityUtils.toString(response.getEntity());
    			}
    			String errorMessage = parseErrorMessage(httpResult);
    			if (errorMessage == null) {
    				Map<String, String> results = new HashMap<String, String>();
    				Log.d("SFStats", "RESULT: " + httpResult);
    				JSONObject jsonParser = new JSONObject(httpResult);
    				String profileViews = jsonParser.getString("profileviews");
    				results.put("profileviews", profileViews);
    				String watches = jsonParser.getString("watches");
    				results.put("watches", watches);
    				
    				return results;
    			}

    		} catch (ClientProtocolException e) {
    			Log.e("getNewImageUrl", "Exception: ", e);
    		} catch (IOException e) {
    			Log.e("getNewImageUrl", "Exception: ", e);
    		} catch (JSONException e) {
    			Log.e("getNewImageUrl", "Exception: ", e);
    		}

    		return null;
    	}

    	protected String parseErrorMessage(String httpResult) {
    		try {
    			// check for json error message and parse it
    			Log.d("Chat.parseErrorMessage", "response: " + httpResult);
    			JSONObject jsonParser;
    			jsonParser = new JSONObject(httpResult);
    			int messageType = jsonParser.getInt("messageType");
    			if (messageType == AJAXTYPE_APIERROR) {
    				String error = jsonParser.getString("error");
    				Log.e("ChatList.parseErrorMessage", "Error: " + error);
    				return error;
    			}
    		} catch (JSONException e) {
    			Log.e("Chat.parseResponse", e.toString());
    		}

    		return null;

    	}

    }
    
    
    
}
